using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using ClientLogic;
using System.Net;
using MsgLogic;

namespace ChatClientApp
{
    public partial class ChatClientAppForm : Form
    {
        private ConnectDialog dialog;
        private Client chatClient;
        private bool continueRunning;
        private string userName;

        public ChatClientAppForm()
        {
            InitializeComponent();
            txtSentMessages.TextChanged += new EventHandler(textBox2_TextChanged);
            continueRunning = false;
            chatClient = null;
        }

       

        private void connectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dialog = new ConnectDialog();
            DialogResult dr = dialog.ShowDialog();
            if (dr == DialogResult.OK)
            {
                if (ValidateConnectDetails())
                {
                    if (chatClient == null)
                    {
                        userName = dialog.txtNickName.Text;
                        chatClient = new Client(IPAddress.Parse(dialog.txtIPAddress.Text), Int32.Parse(dialog.numericUpDownPort.Value.ToString()), dialog.txtNickName.Text, dialog.comboBoxColor.SelectedText);
                        //chatClient = new Client(IPAddress.Parse("127.0.0.1"), 100, "akiva", "Blue");
                        chatClient.MsgArrived += new EventHandler<MsgArrivedEventArgs>(chatClient_MsgArrived);
                        chatClient.ServerDisconnected += new EventHandler<ServerDisconnectedEventArgs>(chatClient_ServerDisconnected);
                        try
                        {
                            chatClient.Connect(backgroundWorker1);
							txtSentMessages.Enabled = true;
                        }
                        catch (Exception ex)
                        {
                            chatClient = null;
                            MessageBox.Show("Chat Server is not available");
							MessageBox.Show(ex.Message);
                            return;
                        }
                        
                        chatClient.SendMsg(new StartMsg(userName));
                        lock (this)
                        {
                            continueRunning = true;
                        }
                       // backgroundWorker1.RunWorkerAsync();

                        
                        //after successful connection - change caption
                        this.Text = "Chat Client - Connected";
                    }
                    
                }
                else
                {

                    MessageBox.Show("Please Correct values");
                    connectToolStripMenuItem_Click(null, null);
                    return;
                }
             
            }
        }

        void chatClient_ServerDisconnected(object sender, ServerDisconnectedEventArgs e)
        {
            try
            {
                backgroundWorker1.ReportProgress(3, e);
            }
            catch (Exception)
            {

            }
            
            
        }

        void chatClient_MsgArrived(object sender, MsgArrivedEventArgs e)
        {
            if (e.Msg as StartMsg != null)
            {
                //Console.WriteLine(e.Msg.UserName + " has just connected");
                //txtArrivedMessages.AppendText(e.Msg.UserName + " has just connected" + '\n');
                backgroundWorker1.ReportProgress(1, e.Msg);
            }
            else if (e.Msg as InfoMsg != null)
            {
                backgroundWorker1.ReportProgress(2, e.Msg);
               
            }
            else   //disconnect
            {
                if (e.Msg.UserName == "Server")
                {
                    chatClient_ServerDisconnected(null, null);
                }
                else
                {
                    chatClient.Disconnect();
                    chatClient = null;
                    backgroundWorker1.ReportProgress(0, e.Msg);
                    
                }
            }
        }
     
        private void disconnectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (chatClient != null)
            {
                lock (this)
                {
                    continueRunning = false;
                }
                //chatClient.SendMsg(new DisconnectMsg(userName));
                //backgroundWorker1.CancelAsync();
                chatClient.Disconnect(backgroundWorker1);
                chatClient = null;
                //after successful disconnection - change caption
                this.Text = "Chat Client - Disconnected";
            }
            
        }

        private bool ValidateConnectDetails()
        {
            bool validated = true;  //change to false
            string pattern = @"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b";
            Match m = Regex.Match(dialog.txtIPAddress.Text, pattern);

            if (m.Success)
            {
                if (dialog.numericUpDownPort.Value > 0)
                {
                    if (dialog.txtNickName.Text != string.Empty)
                    {
                        if (dialog.comboBoxColor.SelectedText != string.Empty)
                        {
                            validated = true;
                        }
                    }

                }
            }
            return validated;
        }

        void textBox2_TextChanged(object sender, EventArgs e)
        {
            if (txtSentMessages.TextLength > 0)
            {
                btnSend.Enabled = true;
            }
            else
            {
                btnSend.Enabled = false;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (chatClient != null)
            {
                chatClient.SendMsg(new TextMsg(dialog.txtNickName.Text, txtSentMessages.Text, Color.FromName(dialog.comboBoxColor.Text)));
                //txtArrivedMessages.AppendText(txtSentMessages.Text + '\n');
                txtSentMessages.Text = string.Empty;
            }
            
        }

        //private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        //{
        //    while (continueRunning)
        //    {
        //        //System.Threading.Thread.Sleep(1000);
        //    }
        //}

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            
            if (e.ProgressPercentage == 1)
            {
                ListViewItem item1 = new ListViewItem();
                item1.SubItems[0].Text = ((TextMsg)e.UserState).UserName + " said:" + '\n';
                item1.SubItems[0].ForeColor = Color.Black;

                ListViewItem item2 = new ListViewItem();

                item2.SubItems[0].Text = "   " + ((TextMsg)e.UserState).UserName + " has just connected" + '\n';
                item2.SubItems[0].ForeColor = ((TextMsg)e.UserState).MsgColor;

                listViewMessages.Items.Add(item1);
                listViewMessages.Items.Add(item2);

            }
            else if (e.ProgressPercentage == 0)
            {
                ListViewItem item1 = new ListViewItem();
                item1.SubItems[0].Text = ((TextMsg)e.UserState).UserName + " said:" + '\n';
                item1.SubItems[0].ForeColor = Color.Black;

                ListViewItem item2 = new ListViewItem();

                item2.SubItems[0].Text = "   " + ((TextMsg)e.UserState).UserName + " disconnected" + '\n';
                item2.SubItems[0].ForeColor = Color.Black;
                listViewMessages.Items.Add(item1);
                listViewMessages.Items.Add(item2);

                if (userName == ((TextMsg)e.UserState).UserName)
                {
                    //after successful disconnection - change caption
                    this.Text = "Chat Client - Disconnected";
					this.chatClient = null;
                }
            }
            else if (e.ProgressPercentage == 2)
            {
                ListViewItem item1 = new ListViewItem();
                item1.SubItems[0].Text = ((TextMsg)e.UserState).UserName + " said:" + '\n';
                item1.SubItems[0].ForeColor = Color.Black;

                ListViewItem item2 = new ListViewItem();

                item2.SubItems[0].Text = "   " + ((TextMsg)e.UserState).Txt + '\n';
                item2.SubItems[0].ForeColor = ((TextMsg)e.UserState).MsgColor;

                listViewMessages.Items.Add(item1);
                listViewMessages.Items.Add(item2);

                //check if the client was disconnected by the server

                if (((TextMsg)e.UserState).Txt.Contains(userName + " disconnected"))
                {
                    //after successful disconnection - change caption
                    this.Text = "Chat Client - Disconnected";
					txtSentMessages.Enabled = false;
					this.chatClient = null;	
                }
                
            }
            else if (e.ProgressPercentage == 3)
            {
                ListViewItem item1 = new ListViewItem();
                item1.SubItems[0].Text = "Server said:" + '\n';
                item1.SubItems[0].ForeColor = Color.Black;

                ListViewItem item2 = new ListViewItem();

                item2.SubItems[0].Text = "   " + "Chat is offline now"+ '\n';
                item2.SubItems[0].ForeColor = Color.Black;

                listViewMessages.Items.Add(item1);
                listViewMessages.Items.Add(item2);

                this.Text = "Chat Client - Disconnected";
				this.chatClient = null;
            }

            listViewMessages.EnsureVisible(listViewMessages.Items.Count - 1);
        }

        private void ChatClientAppForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            DisconnectDialog dialog = new DisconnectDialog();
            DialogResult dr = dialog.ShowDialog();

            if (dr == DialogResult.Yes)
            {
                e.Cancel = false;
                disconnectToolStripMenuItem_Click(this, null);
            }
            else
                e.Cancel = true;
        }

        

    }
}
